package com.logic.landseaserver.service.impl;

import com.logic.common.domain.Code;
import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.common.ws.dto.system.FileDTO;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.PropertyStatusEnum;
import com.logic.landseaserver.common.enums.PropertyStatusHistoryEnum;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.domain.Property;
import com.logic.landseaserver.domain.PropertySign;
import com.logic.landseaserver.domain.PropertyStatusHistory;
import com.logic.landseaserver.persistence.read.*;
import com.logic.landseaserver.persistence.write.PropertyWriteMapper;
import com.logic.landseaserver.service.Action;
import com.logic.landseaserver.service.IProperty;
import com.logic.landseaserver.service.utils.ExcelUtil;
import com.logic.landseaserver.ws.dto.*;
import com.logic.landseaserver.ws.request.PropertyReq;
import com.logic.landseaserver.ws.request.PropertyStatusHistoryReq;
import com.logic.landseaserver.ws.request.StatisticsByStatusReq;
import com.logic.landseaserver.ws.request.SuspendPropertyReq;
import com.logic.landseaserver.ws.response.PropertyDetailResp;
import com.logic.landseaserver.ws.response.StatisticsByStatusResp;
import com.logic.system.domain.Address;
import com.logic.system.domain.Role;
import com.logic.system.domain.SystemFile;
import com.logic.system.domain.User;
import com.logic.system.service.ICodeService;
import com.logic.system.service.IFileService;
import com.logic.system.service.IUserService;
import com.logic.system.service.impl.AddressService;
import com.logic.system.ws.dto.AddressDto;
import com.logic.system.ws.dto.FileConverter;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;


@Service
public class PropertyServiceImpl implements IProperty {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private AddressService addressService;
    @Autowired
    private PropertyWriteMapper propertyWriteMapper;
    @Autowired
    private PropertyReadMapper propertyReadMapper;
    @Autowired
    private PropertySignReadMapper propertySignReadMapper;
    @Autowired
    private PropertyCheckReadMapper propertyCheckReadMapper;
    @Autowired
    private PropertyDecisionReadMapper propertyDecisionReadMapper;
    @Autowired
    private PropertySignEstimationReadMapper propertySignEstimationReadMapper;
    @Autowired
    private ICodeService codeService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private IUserService userService;

    /**
     * 添加物业信息
     *
     * @param o
     * @return
     * @throws BusinessException
     */
    @Override
    public int insert(Object o) throws BusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        validateForInsert(o);

        PropertyReq req = (PropertyReq) o;
        Code city = codeService.getCode(req.getCityCode());
        if (city == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_CITYCODE_IS_NULL);
        }
        Property property = PropertyReq.toPropertyPOJO(req);

        //唯一性校验
        if (propertyReadMapper.checkUniqueName(property) > 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_NAME_IS_NOT_UNIQUE);
        }

        //插入地址
        Address address = req.getAddress();
        addressService.insert(address);

        if (address.getId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESS_ADD_FAILER);
        }

        property.setAddressId(address.getId());
        Integer maxCode = propertyReadMapper.getMaxCityCode(property.getCity());
        property.setIsSuspend(false);
        property.setCode(city.getOther1().trim() + new DecimalFormat("00").format(maxCode));
        property.setCity(req.getCityCode());
        if (property.getStatus() == null) {
            property.setStatus(PropertyStatusEnum.PS1.toString());
        }
        property.updateCommonInfo(userId);
        propertyWriteMapper.insertSelective(property);

        if (property.getId() != null) {
            PropertyStatusHistory hist = new PropertyStatusHistory(PropertyStatusHistoryEnum.PSH1.toString(), new Date(), property.getId());
            propertyWriteMapper.insertPropertyStatusHistory(hist);
            return property.getId();
        } else {
            return 0;
        }
    }

    /**
     * 获取物业详情
     *
     * @param integer
     * @return
     * @throws BusinessException
     */
    @Override
    public Object get(Integer integer) throws BusinessException {


        PropertyDetailResp detailResp = propertyReadMapper.selectDetailById(integer);

        List<FileDTO> drawingList = new ArrayList<>();
        if (!StringUtils.isEmpty(detailResp.getDrawingId())) {
            String[] drawingId = detailResp.getDrawingId().split(",");
            for (String fileId : drawingId) {
                drawingList.add(FileConverter.fromFileToDTO((SystemFile) this.fileService.get(fileId)));
            }
        }
        detailResp.setDrawingList(drawingList);
        List<FileDTO> estateCertList = new ArrayList<>();
        if (!StringUtils.isEmpty(detailResp.getEstateCertId())) {
            String[] estateCertId = detailResp.getEstateCertId().split(",");
            for (String fileId : estateCertId) {
                estateCertList.add(FileConverter.fromFileToDTO((SystemFile) this.fileService.get(fileId)));
            }
        }
        detailResp.setEstateCertList(estateCertList);
        List<FileDTO> ownerAttachmentList = new ArrayList<>();
        if (!StringUtils.isEmpty(detailResp.getOwnerAttachmentId())) {
            String[] ownerAttachmentId = detailResp.getOwnerAttachmentId().split(",");
            for (String fileId : ownerAttachmentId) {
                ownerAttachmentList.add(FileConverter.fromFileToDTO((SystemFile) this.fileService.get(fileId)));
            }
        }
        detailResp.setOwnerAttachmentList(ownerAttachmentList);


        if (detailResp.getAddressId() != null) {
            detailResp.setAddressDto(addressService.queryDetailById(detailResp.getAddressId()));
        }
        return detailResp;
    }

    /**
     * 修改物业信息
     *
     * @param o
     * @throws BusinessException
     */
    @Override
    @Action(name="编辑")
    public void update(Object o) throws BusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }

        validateForUpdate(o);
        PropertyReq req = (PropertyReq) o;
        Property propertyParam = PropertyReq.toPropertyPOJO(req);

        //查看目前物业选址状态
        Property property = propertyReadMapper.selectByPrimaryKey(req.getId());
        if (property == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_UDPATE_PROPERTY_IS_NULL);
        }

        //是否是草稿阶段
        if (!property.getStatus().equals(PropertyStatusEnum.PS1.toString()) && !property.getStatus().equals(PropertyStatusEnum.PS2.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_UDPATE_PS1_IS_NOT);
        }

        //判断城市是否存在
        Code city = codeService.getCode(req.getCityCode());
        if (city == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_CITYCODE_IS_NULL);
        }

        //唯一性校验
        if (propertyReadMapper.checkUniqueName(propertyParam) > 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_NAME_IS_NOT_UNIQUE);
        }


        //如果城市改变，则重新编码
        if (!property.getCity().equals(propertyParam.getCity())) {
            Integer maxCode = propertyReadMapper.getMaxCityCode(req.getCityCode());
            propertyParam.setCode(city.getOther1().trim() + new DecimalFormat("00").format(maxCode));
        }
        if (property.getStatus().equals(PropertyStatusEnum.PS5.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_UDPATE_PS5_IS_NULL);
        }
        if (property.getIsSuspend()) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_UDPATE_ISSUSPEND_IS_NULL);
        }
        //修改地址
        addressService.update(req.getAddress());
        propertyParam.updateCommonInfo(userId);
        propertyParam.setLease(propertyParam.getLease());
        propertyWriteMapper.updateByPrimaryKeySelective(propertyParam);
        //修改租期bug
        propertyWriteMapper.updateLeaseById(propertyParam);
    }

    /**
     * 删除物业
     *
     * @param s
     * @throws BusinessException
     */
    @Override
    public void delete(String s) throws BusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        if (StringUtils.isEmpty(s)) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IDS_IS_NULL);
        }
        if (s.split(",").length == 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IDS_IS_NULL);
        }
        if (propertyReadMapper.checkPropertyStatus(s.split(",")) > 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_EXSIT_PS2_PROPERTY);
        }
        Map map = new HashMap<>();
        map.put("userId", userId);
        map.put("list", s.split(","));
        propertyWriteMapper.delete(map);
    }

    @Override
    public List<Object> query(QueryUtil queryUtil) {
        return null;
    }

    /**
     * 查询物业选址列表
     *
     * @param queryUtil
     * @return
     */
    @Override
    public List<PropertyDTO> queryPage(QueryUtil queryUtil) {
        List<PropertyDTO> list = new ArrayList<>();
        Map<String, Object> map = queryUtil.getParams();
        if (map == null) {
            return list;
        }
        Integer userId = (Integer) map.get("userId");
        if (userId == null) {
            return list;
        }

        User user = null;
        try {
            user = (User) userService.get(userId);
        } catch (BusinessException e) {
            return list;
        }
        if (user == null) {
            return list;
        }
        if (user.getRoleList() != null && user.getRoleList().size() > 0) {
            Map<String, Object> params = queryUtil.getParams();

            //是否超管
            Integer isRoot = new Integer(0);
            //是否拓展员
            Integer isDev = new Integer(0);
            for (Role role : user.getRoleList()) {
                if ("DEVMANAGER".equals(role.getCode())) {
                    isDev = 1;
                }
                if ("ROOT".equals(role.getCode())) {
                    isRoot = 1;
                }
            }
            params.put("isRoot", isRoot);
            params.put("isDev", isDev);
            params.put("userId", userId);
            list = propertyReadMapper.queryPropertyPage(queryUtil);

            if (list.size() > 0) {
                for (PropertyDTO propertyDTO : list) {
                    if (propertyDTO.getAddressId() != null) {
                        propertyDTO.setAddressDto(addressService.queryDetailById(propertyDTO.getAddressId()));
                    }
                }
            }
            return list;
        } else {
            return list;
        }

    }

    @Override
    public List<StatisticsByStatusResp> statisticsByStatus(StatisticsByStatusReq req) throws LandseaBusinessException {
        List<StatisticsByStatusResp> list = new ArrayList<>();

        if (req.getUserId() == null) {
            return list;
        }
        User user = null;
        try {
            user = (User) userService.get(req.getUserId());
        } catch (BusinessException e) {
            return list;
        }
        if (user == null) {
            return list;
        }
        if (user.getRoleList() != null && user.getRoleList().size() > 0) {

            //是否超管
            Integer isRoot = new Integer(0);
            //是否拓展员
            Integer isDev = new Integer(0);
            for (Role role : user.getRoleList()) {
                if ("DEVMANAGER".equals(role.getCode())) {
                    isDev = 1;
                }
                if ("ROOT".equals(role.getCode())) {
                    isRoot = 1;
                }
            }
            if (req == null) {
                req = new StatisticsByStatusReq();
            }
            req.setIsDev(isDev);
            req.setIsRoot(isRoot);
            list = propertyReadMapper.statisticsByStatus(req);
        }

        return list;
    }

    @Override
    public Boolean validate(Object o) throws BusinessException {
        return null;
    }

    @Override
    public Boolean validateForInsert(Object o) throws BusinessException {
        PropertyReq req = (PropertyReq) o;

        if (req == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_OBJ_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getName())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_NAME_IS_NULL);
        }

        if (req.getArea() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_AREA_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getCityCode())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_CITYCODE_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getType())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_TYPE_IS_NULL);
        }
        if (req.getRent() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_RENT_IS_NULL);
        }

        if (req.getRentYearPlus() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_RENTYEARPLUS_IS_NULL);
        }
        if (req.getRentPercentagePlus() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_RENTPERCENTAGEPLUS_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getPayMethod())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_PAYMETHOD_IS_NULL);
        }
        if (req.getFee() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_FEE_IS_NULL);
        }
        if (req.getAddress() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getProvince())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_PROVINCE_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getCity())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_CITY_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getCounty())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_COUNTY_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getAddressLine1())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_ADDRESS_IS_NULL);
        }
        if (req.getRentFree() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_RENTFREE_IS_NULL);
        }

        if (req.getInvoiceType() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_INVOICETYPE_IS_NULL);
        }
        if (req.getInvoiceType() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_INVOICETYPE_IS_NULL);
        }

        return null;
    }

    @Override
    public Boolean validateForUpdate(Object o) throws BusinessException {
        PropertyReq req = (PropertyReq) o;

        if (req == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_OBJ_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getId())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ID_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getName())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_NAME_IS_NULL);
        }

        if (req.getArea() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_AREA_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getCityCode())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_CITYCODE_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getType())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_TYPE_IS_NULL);
        }
        if (req.getRent() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_RENT_IS_NULL);
        }
        if (req.getRentYearPlus() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_RENTYEARPLUS_IS_NULL);
        }
        if (req.getRentPercentagePlus() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_RENTPERCENTAGEPLUS_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getPayMethod())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_PAYMETHOD_IS_NULL);
        }
        if (req.getFee() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_FEE_IS_NULL);
        }
        if (req.getAddress() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_IS_NULL);
        }
        if (req.getAddress().getId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSID_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getProvince())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_PROVINCE_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getCity())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_CITY_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getCounty())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_COUNTY_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getAddress().getAddressLine1())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_ADDRESSDTO_ADDRESS_IS_NULL);
        }
        if (req.getInvoiceType() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_INVOICETYPE_IS_NULL);
        }
        return null;
    }

    @Override
    public Boolean validateForDelete(Object o) throws BusinessException {
        return null;
    }

    /**
     * 中止物业
     *
     * @param req
     * @throws LandseaBusinessException
     */
    @Override
    @Action(name="中止")
    public void suspendProperty(SuspendPropertyReq req) throws LandseaBusinessException {

        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        Property property = propertyReadMapper.selectByPrimaryKey(req.getId());
        //是否立项
        if (property.getStatus().equals(PropertyStatusEnum.PS5.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_SUSPEND_NO_ACCESS);
        }
        //是否是草稿阶段
        if (property.getStatus().equals(PropertyStatusEnum.PS1.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_SUSPEND_PS1_NO_ACCESS);
        }
        //是否已经中止
        if (property.getIsSuspend()) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_HAS_SUSPEND);
        }
        Property p = new Property();
        p.setId(req.getId());
        p.setIsSuspend(true);
        p.setSuspendDate(new Date());
        p.setSuspendCause(req.getReason());
        p.updateCommonInfo(userId);
        propertyWriteMapper.updateByPrimaryKeySelective(p);

        PropertyStatusHistory hist = new PropertyStatusHistory();
        hist.setPropertyId(property.getId());
        hist.setComment(req.getReason());
        hist.setStatus(PropertyStatusHistoryEnum.PSH6.toString());
        hist.setTime(new Date());
        propertyWriteMapper.insertPropertyStatusHistory(hist);
    }

    /**
     * 再次开启物业项目
     *
     * @param req
     * @throws LandseaBusinessException
     */
    @Override
    @Action(name="启动")
    public void contineProperty(PropertyStatusHistoryReq req) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }

        Property property = propertyReadMapper.selectByPrimaryKey(req.getId());
        if (property == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_PROPERTY_IS_NULL);
        }
        if (!property.getIsSuspend()) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CONTINUE_IS_ACTIVE);
        }

        Property p = new Property();
        p.setId(req.getId());
        p.setIsSuspend(false);
        p.updateCommonInfo(userId);
        propertyWriteMapper.updateByPrimaryKeySelective(p);

        //增加操作记录
        PropertyStatusHistory hist = PropertyStatusHistoryReq.convertFromDTO(req);
        hist.setStatus(PropertyStatusHistoryEnum.PSH7.toString());
        propertyWriteMapper.insertPropertyStatusHistory(hist);
    }

    /**
     * 审批通过
     *
     * @param req
     * @throws LandseaBusinessException
     */
    @Override
    @Action(name="审批通过")
    public void checkSubmit(PropertyStatusHistoryReq req) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }

        Property property = propertyReadMapper.selectByPrimaryKey(req.getId());
        if (property == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_PROPERTY_ID_IS_NULL);
        }
        //是否中止
        if (property.getIsSuspend()) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_HAS_SUSPEND);
        }
        //是否是审批中
        if (!property.getStatus().equals(PropertyStatusEnum.PS2.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IS_NO_PS3);
        }
        //是否有文件上传
        PropertyCheckDTO newCheck = propertyCheckReadMapper.getNewCheck(req.getId());
        if (newCheck == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_SUBMIT_FILE_NULL);
        }

        //只有有一个通过记录
        if (propertyCheckReadMapper.checkTheResult(newCheck.getId()) == 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_SUBMIT_FILERESULT_NULL);
        }

        Property p = new Property();
        p.setId(req.getId());
        p.setStatus(PropertyStatusEnum.PS3.toString());
        p.setCheckDate(new Date());
        p.updateCommonInfo(userId);
        propertyWriteMapper.updateByPrimaryKeySelective(p);

        PropertyStatusHistory hist = PropertyStatusHistoryReq.convertFromDTO(req);
        hist.setStatus(PropertyStatusHistoryEnum.PSH3.toString());
        propertyWriteMapper.insertPropertyStatusHistory(hist);
    }

    /**
     * 立项
     *
     * @param req
     * @throws LandseaBusinessException
     */
    @Override
    @Action(name="立项")
    public void signSubmit(PropertyStatusHistoryReq req) throws LandseaBusinessException {

        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }

        Property property = propertyReadMapper.selectByPrimaryKey(req.getId());

        if (property == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_PROPERTY_ID_IS_NULL);
        }
        if (property.getIsSuspend()) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_HAS_SUSPEND);
        }
        //是否是签订中
        if (!property.getStatus().equals(PropertyStatusEnum.PS4.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IS_NOT_PS4);
        }
        PropertySign propertySign = propertySignReadMapper.hasFinalVersion(req.getId());
        if (propertySign == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_CONTRACT_VERSON_HAS_NOT_FINAL);
        }
        if (propertySignEstimationReadMapper.checkTheSignResult(propertySign.getId()) == 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_CONTRACT_VERSON_HAS_FINAL_NOT_ACCESS);
        }

        Property p = new Property();
        p.setId(req.getId());
        p.setStatus(PropertyStatusEnum.PS5.toString());
        p.setSignDate(new Date());
        p.setDoneDate(new Date());
        p.updateCommonInfo(userId);
        propertyWriteMapper.updateByPrimaryKeySelective(p);

        PropertyStatusHistory hist = PropertyStatusHistoryReq.convertFromDTO(req);
        hist.setStatus(PropertyStatusHistoryEnum.PSH5.toString());
        propertyWriteMapper.insertPropertyStatusHistory(hist);
    }

    /**
     * 上报物业
     *
     * @param req
     * @throws LandseaBusinessException
     */
    @Override
    @Action(name="上报")
    public void reportProperty(PropertyStatusHistoryReq req) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        if (req.getId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_PROPERTY_ID_IS_NULL);
        }
        Property property = propertyReadMapper.selectByPrimaryKey(req.getId());

        if (property == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_REPORT_IS_NULL);
        }
        if (property.getCreatedBy().compareTo(userId) != 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_REPORT_VERSON_IS_NULL);
        }
        if (!property.getStatus().equals(PropertyStatusEnum.PS1.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_REPORT_NOT_ACCESS);
        }

        property.setStatus(PropertyStatusEnum.PS2.toString());
        property.setReportDate(new Date());
        property.updateCommonInfo(userId);
        propertyWriteMapper.updateByPrimaryKeySelective(property);
        //增加操作记录
        PropertyStatusHistory hist = PropertyStatusHistoryReq.convertFromDTO(req);
        hist.setStatus(PropertyStatusHistoryEnum.PSH2.toString());
        propertyWriteMapper.insertPropertyStatusHistory(hist);
    }

    @Override
    @Action(name="投决通过")
    public void decisionSubmit(PropertyStatusHistoryReq req) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        if (req.getId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_PROPERTY_ID_IS_NULL);
        }
        Property property = propertyReadMapper.selectByPrimaryKey(req.getId());

        if (property == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_REPORT_IS_NULL);
        }
        //是否是投决阶段
        if (!property.getStatus().equals(PropertyStatusEnum.PS3.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_REPORT_NOT_ACCESS);
        }
        //是否有通过记录
        if (propertyDecisionReadMapper.getTheResult(req.getId()) == 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DECISION_DECISION_ISNULL);
        }

        property.setStatus(PropertyStatusEnum.PS4.toString());
        property.setDecisionDate(new Date());
        property.updateCommonInfo(userId);
        propertyWriteMapper.updateByPrimaryKeySelective(property);
        //增加操作记录
        PropertyStatusHistory hist = PropertyStatusHistoryReq.convertFromDTO(req);
        hist.setStatus(PropertyStatusHistoryEnum.PSH4.toString());
        propertyWriteMapper.insertPropertyStatusHistory(hist);
    }

    /**
     * 导出物业列表
     *
     * @param response
     * @param util
     */
    public void exportPropertyList1(HttpServletResponse response, QueryUtil util) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setContentType("APPLICATION/OCTET-STREAM");
        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String("物业选址列表".getBytes("gb2312"), "ISO8859-1") + ".xls");
        } catch (UnsupportedEncodingException e) {
            logger.error("exportPropertyList1 error.", e);
        }
        OutputStream out = null;

        List<PropertyDTO> list = new ArrayList<>();

        list = this.queryPage(util);
        for (PropertyDTO dto : list) {
            dto.setPlus(dto.getRentYearPlus() + "年" + dto.getRentPercentagePlus() + "%");
        }

        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            logger.error("exportPropertyList1 error.", e);
        }
        List[] listArray = {list};
        ExcelUtil<PropertyDTO> exportUitil = new ExcelUtil<PropertyDTO>(
                PropertyDTO.class);// 创建excel工具类
        String[] titleArray = {"物业选址列表"};
        exportUitil.exportExcel(listArray, titleArray, out);// 导出
    }


    /**
     * 导出物业列表
     *
     * @param response
     * @param ids
     */
    @Override
    public void exportPropertyList(HttpServletResponse response, String ids) {
        InputStream ins = null;
        Workbook wb = null;
        try {
            ins = PropertyServiceImpl.class.getClassLoader().getResourceAsStream("物业选址导出模板.xlsx");
            wb = WorkbookFactory.create(ins);
        } catch (FileNotFoundException e) {
            logger.error("exportPropertyList error.", e);
        } catch (IOException e) {
            logger.error("exportPropertyList error.", e);
        } catch (InvalidFormatException e) {
            logger.error("exportPropertyList error.", e);
        } finally {
            try {
                ins.close();
            } catch (IOException e) {
                logger.error("exportPropertyList error.", e);
            }
        }
        String fileName = "物业选址.xlsx";
        List<PropertyDTO> list = propertyReadMapper.queryReportPage(ids.split(","));
        if (list != null && list.size() > 0) {
            Sheet sheet = wb.getSheet("物业选址列表");
            // 生成一个样式
            CellStyle style = wb.createCellStyle();
            // 设置这些样式
            style.setAlignment(CellStyle.ALIGN_CENTER);
            // 生成一个字体
            Font font = wb.createFont();
            font.setFontHeightInPoints((short) 14);
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            // 把字体应用到当前的样式
            style.setFont(font);

            Row row;
            Cell cell;// 产生单元格

            int startRow = 2;
            for (int i = 0; i < list.size(); i++) {
                PropertyDTO object = list.get(i);
                row = sheet.createRow(startRow);
                row.createCell(0).setCellValue(i+1);
                row.createCell(1).setCellValue(object.getCode());
                row.createCell(2).setCellValue(object.getName());
                row.createCell(3).setCellValue(object.getType());
                row.createCell(4).setCellValue(object.getStatus());
                row.createCell(5).setCellValue(object.getCity());
                row.createCell(6).setCellValue(object.getArea());
                row.createCell(7).setCellValue(object.getRent());
                row.createCell(8).setCellValue(object.getRentYearPlus() + "年" + object.getRentPercentagePlus() + "%");
                row.createCell(9).setCellValue(object.getPayMethod());
                row.createCell(10).setCellValue(object.getFee());
                row.createCell(11).setCellValue(object.getLease() == null ? "" : object.getLease().toString());
                row.createCell(12).setCellValue(object.getRentFree());
                row.createCell(13).setCellValue(object.getSuspend());
                row.createCell(14).setCellValue(object.getSuspend().equals("已中止") ? object.getSuspendDate() : "");
                row.createCell(15).setCellValue(object.getCreatedBy());
                row.createCell(16).setCellValue(object.getCreatedDate());
                row.createCell(17).setCellValue(object.getReportDate());
                row.createCell(18).setCellValue(object.getCheckDate());
                row.createCell(19).setCellValue(object.getDecisionDate());
                row.createCell(20).setCellValue(object.getSignDate());
                row.createCell(21).setCellValue(object.getDoneDate());
                //测算文件
                PropertyCheckDTO newCheck = propertyCheckReadMapper.getNewCheck(object.getId());
                row.createCell(22).setCellValue(newCheck == null ? "" : newCheck.getEstimationName());
                row.createCell(23).setCellValue(newCheck == null ? "" : "V" + newCheck.getEstimationVerison() + ".0");
                row.createCell(24).setCellValue(newCheck == null ? "" : newCheck.getCreatedDtmString());

                row.createCell(25).setCellValue(newCheck == null ? "" : newCheck.getCreatedByName());
                PropertyDecisionDTO decision = propertyDecisionReadMapper.getNewDecision(object.getId());
                row.createCell(26).setCellValue(decision == null ? "" : decision.getBusinessCondition());
                row.createCell(27).setCellValue(decision == null ? "" : decision.getSummaryName());
                row.createCell(28).setCellValue(decision == null ? "" : decision.getDecisionDate());
                row.createCell(29).setCellValue(decision == null ? "" : decision.getDecisionResult());
                PropertySignDTO sign = propertySignReadMapper.getNewSign(object.getId());
                row.createCell(30).setCellValue(sign == null ? "" : sign.getContractName());
                if (sign == null) {
                    row.createCell(31).setCellValue("");
                } else if (sign.getFinalflag()) {
                    row.createCell(31).setCellValue("签订版");
                } else {
                    row.createCell(31).setCellValue("V" + sign.getSignVersion() + ".0");
                }
                row.createCell(32).setCellValue(sign == null ? "" : sign.getCreatedDtm());

                row.createCell(33).setCellValue(sign == null ? "" : sign.getCreatedBy());
                startRow = startRow + 1;
            }
            //总计
            row = sheet.createRow(startRow);
            row.createCell(0).setCellValue("总计");
            row.createCell(7).setCellFormula("SUM(H3:F"+startRow+")");

            //修改数据行样式
            for (int i = 2 ; i <= startRow ;i++) {
                Row modelRow = sheet.getRow(1);
                Row distRow = sheet.getRow(i);
                //遍历一行中的所有的单元格
                for (int j  = 0 ; j <=33;j++) {
                    if(distRow.getCell(j) == null){
                        distRow.createCell(j);
                    }
                    distRow.getCell(j).setCellStyle( modelRow.getCell(j).getCellStyle());
                    //最后一行加粗
                    if(i == startRow && j>=1 ){
                        CellStyle tempStyle = wb.createCellStyle(); //样式
                        tempStyle.cloneStyleFrom( modelRow.getCell(j).getCellStyle());
                        tempStyle.setBorderBottom(modelRow.getCell(1).getCellStyle().getBorderLeft());
                        distRow.getCell(j).setCellStyle(tempStyle);
                    }
                }

            }
        }



        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setContentType("APPLICATION/OCTET-STREAM");
        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            logger.error("exportPropertyList error.", e);
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            wb.write(out);
        } catch (IOException e) {
            logger.error("exportPropertyList error.", e);
        }


    }


    /**
     * 查询物业进度
     *
     * @param id
     * @return
     */
    @Override
    public List<PropertyHistoryDTO> queryPropertyHistory(Integer id) {
        return propertyReadMapper.queryPropertyHistory(id);
    }


    @Override
    public List<PropertyDTO> queryDTO(QueryUtil queryUtil) {
    	List<PropertyDTO> list = propertyReadMapper.queryDTO(queryUtil);
        if (list.size() > 0) {
            for (PropertyDTO propertyDTO : list) {
                Integer addressId = propertyDTO.getAddressId();
            	if (addressId != null) {
                	StringBuffer fullName = new StringBuffer();
                	AddressDto addressDto = addressService.queryDetailById(addressId);
            		if(addressDto != null) {
            			String province = addressDto.getProvince();
            			String city = addressDto.getCity();
            			String county = addressDto.getCounty();
            			String addressLine = addressDto.getAddressLine();
            			fullName.append(province == null ? "" : province).append(city == null ? "" : city).append(county == null ? "" : county)
            			.append(addressLine == null ? "" : addressLine);
            			addressDto.setFullAddress(fullName.toString());
                        propertyDTO.setAddressDto(addressDto);
                  }
            }
        }
    }
        return list;
    }

}
